﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.Approval;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.Approval
{
 

    public class UpLeaveApplicationCommendHandlers : IRequestHandler<UpLeaveApplicationCommends, APIResult<LeaveApplications>>
    {

        private readonly IBaseRepository<LeaveApplications> leaveapplicationRepository;
        private readonly IMapper mapper;

        public UpLeaveApplicationCommendHandlers(IBaseRepository<LeaveApplications> leaveapplicationRepository, IMapper mapper)
        {
            this.leaveapplicationRepository = leaveapplicationRepository;
            this.mapper = mapper;
        }



        /// <summary>
        /// 修改申请表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<LeaveApplications>> Handle(UpLeaveApplicationCommends request, CancellationToken cancellationToken)
        {
            APIResult<LeaveApplications> result = new APIResult<LeaveApplications>();
            result.Code = APIEnum.修改成功;
            result.Msg = "修改成功";
            var leaveapplication = mapper.Map<LeaveApplications>(request);
            leaveapplication.CreateTime = DateTime.Now;
            leaveapplication.UserName = request.UserName;
            leaveapplication.DepId = request.DepId;
            leaveapplication.Status = 0;
            leaveapplication.DepheadsName = request.DepheadsName;
            leaveapplication.StartTime = request.StartTime.AddHours(8);
            leaveapplication.EndTime = request.EndTime.AddHours(8);
            // 计算请假时长和总工时
            TimeSpan duration = leaveapplication.EndTime - leaveapplication.StartTime;
            long totalHours = (long)duration.TotalHours;
            leaveapplication.Leavetime = leaveapplication.EndTime.ToString("yyyy-MM-dd") + "至" + leaveapplication.StartTime.ToString("yyyy-MM-dd");
            leaveapplication.Totalhours = request.Totalhours;
            await leaveapplicationRepository.Update(leaveapplication);

            return await Task.FromResult(result);
        }
    }
}
